package com.sapp.imagecolorization

import android.Manifest.permission.*
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.facebook.drawee.backends.pipeline.Fresco
import com.sapp.imagecolorization.image_settings.ImageSettings
import com.sapp.imagecolorization.retrofit.RestApiService
import com.sapp.imagecolorization.retrofit.imageUrlToDownload
import com.sapp.imagecolorization.utils.RuntimePermission
import com.sapp.imagecolorization.utils.Utils
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File
import java.text.SimpleDateFormat
import java.util.*


class MainActivity : AppCompatActivity() {
    private val restApiService =
        RestApiService()
    private val permission = RuntimePermission()
    private val REQUEST_READ_STORAGE_AND_CAMERA = 1
    private val REQUEST_PICK_IMAGE = 2
    private val REQUEST_IMAGE_CAPTURE = 3
    private val permissions = arrayOf(READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE, CAMERA)
    private val imageSettings = ImageSettings()
    private val utils = Utils()
    private var pictureImagePath = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Fresco.initialize(this)

        setContentView(R.layout.activity_main)

        // Requesting permission
        permission.checkPermission(this, permissions, REQUEST_READ_STORAGE_AND_CAMERA) {}

        clickEvents()
    }

    private fun clickEvents() {
        select_image.setOnClickListener {
            imageSettings.selectPhoto(
                this,
                permissions,
                REQUEST_READ_STORAGE_AND_CAMERA,
                REQUEST_PICK_IMAGE
            )
        }

        make_photo.setOnClickListener {
            openBackCamera()
        }

        select_link.setOnClickListener {
            utils.showLinkPopup(this, main_page_layout, image_frame, progress_bar, restApiService)
        }

        do_with_image.setOnClickListener {
            permission.checkPermission(this, permissions, REQUEST_READ_STORAGE_AND_CAMERA) {
                if (imageUrlToDownload != "") {
                    if (do_with_image_container.visibility == View.VISIBLE) {
                        do_with_image_container.visibility = View.GONE
                    } else {
                        do_with_image_container.visibility = View.VISIBLE
                    }
                } else {
                    utils.showToastMessage(
                        this,
                        getString(R.string.please_select_the_image_or_image_link)
                    )
                }
            }

        }

        download_image.setOnClickListener {
            imageSettings.imageDownload(this, imageUrlToDownload)
        }

        share_image.setOnClickListener {
            imageSettings.shareImage(this)
        }

        image_frame.setOnClickListener {

        }

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (requestCode == REQUEST_PICK_IMAGE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                val i = Intent(
                    Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                )

                startActivityForResult(i, REQUEST_PICK_IMAGE)

            } else {
                utils.showToastMessage(this, getString(R.string.permission_not_granted))

            }

            if (requestCode == REQUEST_READ_STORAGE_AND_CAMERA) {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    utils.showToastMessage(this, getString(R.string.permission_granted))
                } else {

                    utils.showToastMessage(this, getString(R.string.permission_not_granted))
                }

            }

        }

    }

    @SuppressLint("SimpleDateFormat")
    private fun openBackCamera() {
        val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
        val imageFileName = "$timeStamp.jpg"
        val storageDir: File = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES
        )

        progress_bar.visibility = View.VISIBLE
        pictureImagePath = storageDir.absolutePath.toString() + "/" + imageFileName
        val file = File(pictureImagePath)
        val imageUri = FileProvider.getUriForFile(
            this@MainActivity,
            "com.sapp.imagecolorization.provider",
            file
        )

        val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
        startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_PICK_IMAGE) {
            if (data != null) {

                val imagePath = data.data!!

                val filePathColumn = arrayOf(MediaStore.Images.Media.DATA)
                val cursor =
                    contentResolver.query(imagePath, filePathColumn, null, null, null)
                cursor!!.moveToFirst()
                val columnIndex = cursor.getColumnIndex(filePathColumn[0])
                val imgDecodableString = cursor.getString(columnIndex)
                cursor.close()

                progress_bar.visibility = View.VISIBLE

                if (imgDecodableString != null) {
                    imageSettings.loadStorageImage(
                        this,
                        restApiService,
                        imgDecodableString,
                        image_frame,
                        progress_bar
                    )

                } else {
                    utils.showToastMessage(this, getString(R.string.something_went_wrong))
                }
            }
        }

        if (requestCode == REQUEST_IMAGE_CAPTURE) {

            val imgFile = File(pictureImagePath)

            if (imgFile.exists()) {
                imageSettings.loadStorageImage(
                    this,
                    restApiService,
                    imgFile.toString(),
                    image_frame,
                    progress_bar
                )

            } else {
                utils.showToastMessage(this, getString(R.string.something_went_wrong))

            }
        }

    }
}